#define LUA_CORE

#include "lua.h"
#include "lauxlib.h"

#include "ldo.h"
#include "lfunc.h"
#include "lmem.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lstring.h"
#include "lundump.h"
#define api_checknelems(L, n)	api_check(L, (n) <= (L->top - L->base))
static int z_lua_dump (lua_State *L, lua_Writer writer, void *data) {
  int status;
  TValue *o;
  lua_lock(L);
  api_checknelems(L, 1);
  o = L->top - 1;
  if (isLfunction(o))
    status = luaU_dump(L, clvalue(o)->l.p, writer, data,1);
  else
    status = 1;
  lua_unlock(L);
  return status;
}
static int writer (lua_State *L, const void* b, size_t size, void* B) {
  (void)L;
  luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
  return 0;
}
static int z_dump(lua_State *L) /** dump(f,...) */
{
	luaL_Buffer b;
	luaL_checktype(L, 1, LUA_TFUNCTION);
	lua_settop(L, 1);
	luaL_buffinit(L,&b);
	if (z_lua_dump(L, writer, &b) != 0)
		luaL_error(L, "unable to dump given function");
	luaL_pushresult(&b);
	return 1;
}

static const luaL_reg R[] =
{
{ "zdump", z_dump },
{ NULL, NULL } };

int luaopen_zdump(lua_State *L)
{
	lua_register(L, "zdump", z_dump);
	return 0;
}
